$LOAD_PATH << '.'
require 'StockPrice'
require 'json'

#
class PriceOp
	@file
	@json_str
	@json
	@sp
	def initialize(file)
		begin
			if !File.readable?(file)
				raise 'file dose not exists'
			end
			@file = file
		rescue Exception=>e
			puts e.message	
		end	
	end

	private

	def save
		f = File.new(@file,'w')
		f.syswrite(@json_str)
	end

	def get
		size = File::size(@file)
		f = File.new(@file,'r')
		content =  f.sysread(size)
		
		begin
			puts content
			@json = JSON.parse(content)		
		rescue Exception=>e
			@json = JSON.parse('{}')
			puts e.message
		end
	end

	public

	def step
		get
		puts "please input the code of stock and its price"

		@sp = StockPrice.new(@json)
		while true
			puts "stock or puts q to quit"
			input = gets.chomp
			if input == "q"
				self.quit
			else
				stockcode =  input			
			end
			puts "price"
			stockprice = gets.chomp
			@sp.set(stockcode,stockprice)	
		end
	end

	def quit
		@json_str = @sp.json
		save	
		exit	
	end
	
end
f = PriceOp.new('price.json')
f.step


